'use strict';

const Controller = require('egg').Controller;

class AddCartController extends Controller {
    async index() {
    
        const { ctx } = this;
        // console.log(ctx.query)
        var {id} = ctx.query;
        //1.对goods表查询获取对应数据
        try{
            var data =await ctx.model.Goods.find({_id:id});
            // console.log(data)
            var item = data[0]
            //2.对CartList进行查询，没有就添加，有酒给前端返回对应值

            // ctx.cookies.set("name","cheng",{
            //   httpOnly:true
            // })
            var res = await ctx.model.User.find({"cartList._id":id.trim()});
            if(res.length == 0){
                await ctx.model.User.updateOne({$push:{cartList:item}})
                ctx.body ={
                    msg:"添加成功",
                    code:200,
                }
            }else{
                ctx.body ={
                    msg:"已经添加至购物车了",
                    code:400,
                }
            }
        }catch(err){
            // console.log(err)
            ctx.body ={
                msg:"输入的id值不合法",
                code:400,
            }
        }
    
    }
}

module.exports = AddCartController;
